import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

import {
	getToken,
	setToken,
	removeToken
} from '@/utils/auth.js'

const store = new Vuex.Store({
	state: {
		token: getToken() ? getToken() : '',
		name: '',
		avatar: '',
		tel: '',
		roleCode: '',
		roleName: '',
		account: ''
	},
	getters: {
		token: (state) => state.token,
		avatar: (state) => state.avatar,
		name: (state) => state.name,
		tel: (state) => state.tel,
		roleCode: (state) => state.roleCode,
		roleName: (state) => state.roleName,
		account: (state) => state.account
	},
	mutations: {
		USER_LOGIN(state, token) {
			state.token = token
			setToken(token)
		},
		USER_LOGOUT(state) {
			state.token = ''
			state.name = ''
			state.account = ''
			state.avatar = ''
			state.tel = ''
			state.roleCode = ''
			state.roleName = ''
		},
		SET_INFO(state, info) {
			const {
				userName,
				userAccount,
				userTel,
				roleCode,
				roleName,
				avatar
			} = info
			state.name = userName
			state.account = userAccount
			state.tel = userTel
			state.avatar = avatar
			state.roleCode = roleCode
			state.roleName = roleName
		},
		CLEAR(state) {
			for (let i in state) {
				delete state[i]
			}
		},

	},
	actions: {
		login(context, token) {
			context.commit('USER_LOGIN', token)
		},
		logout(context) {
			context.commit('USER_LOGOUT')
		},
		setInfo(context, info) {
			context.commit('SET_INFO', info)
		},
		clear(context) {
			context.commit('CLEAR')
		},
	}
})

export default store